package controllers

import (
	"net/http"
	"github.com/gin-gonic/gin"
	"gouniapp/configs"
)

// 获取站内消息列表
func GetMessages(c *gin.Context) {
    // 请求参数结构体
    type MessageRequest struct {
    	Page     int `json:"page" binding:"required,min=1"`
    	PageSize int `json:"pageSize" binding:"required,min=1,max=300"`
    }
	// 获取当前用户
	currentUser := GetCurrentUser(c)
	if currentUser == nil {
		JsonResponse(c, http.StatusUnauthorized, "请重新登录", nil)
		return
	}

	// 绑定JSON参数
	var req MessageRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		JsonResponse(c, http.StatusBadRequest, "参数错误："+err.Error(), nil)
		return
	}

	// 构建查询
	query := configs.DB.Model(&configs.Message{}).Where("user_id = ?", currentUser.ID).Order("created_at DESC")

	var total int64
	var isnotread int64
	var items []configs.Message
	if err := query.Count(&total).Scopes(configs.Paginate(req.Page, req.PageSize)).Find(&items).Error; err != nil {
		JsonResponse(c, http.StatusInternalServerError, "获取数据失败", nil)
		return
	}
	//未读数量
	configs.DB.Model(&configs.Message{}).Where("user_id = ? AND is_read = ?", currentUser.ID, false).Count(&isnotread)
	JsonResponse(c, http.StatusOK, "获取成功", gin.H{
        "items": items,
        "total": total,
        "isnotread": isnotread,
	})
}

// 标记消息已读
func MarkMessageRead(c *gin.Context) {
    type MarkReadRequest struct {
    	MessageID uint `json:"messageId" binding:"required"`
    }
	// 获取当前用户
	currentUser := GetCurrentUser(c)
	if currentUser == nil {
		JsonResponse(c, http.StatusUnauthorized, "请重新登录", nil)
		return
	}
	// 绑定JSON参数
	var req MarkReadRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		JsonResponse(c, http.StatusBadRequest, "参数错误："+err.Error(), nil)
		return
	}
	// 更新操作
	result := configs.DB.Model(&configs.Message{}).Where("id = ? AND user_id = ?", req.MessageID, currentUser.ID).Update("is_read", true)
	if result.Error != nil {
		JsonResponse(c, http.StatusInternalServerError, "更新失败", nil)
		return
	}
	if result.RowsAffected == 0 {
		JsonResponse(c, http.StatusNotFound, "消息不存在或无权操作", nil)
		return
	}
	JsonResponse(c, http.StatusOK, "操作成功", nil)
}